package com.s54.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.s54.common.beans.R;
import com.s54.common.beans.UserInfo;
import com.s54.system.entity.User;
import com.s54.system.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-05-16
 */
@RestController
@RequestMapping("/system/users")
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    @GetMapping
    public R getAll() {
        return R.ok(userService.list());
    }

    @PostMapping
    public R add(@RequestBody User user) {
        userService.save(user);
        return R.ok();
    }

    @DeleteMapping("/{id}")
    public R del(@PathVariable Long id) {
        userService.removeById(id);
        return R.ok();
    }

    @PutMapping
    public R update(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return R.ok();
    }

    @GetMapping("/getUserInfo")
    public R<UserInfo> getUserInfo(String username) {
        User one = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, username));
        if (one == null) {
            return R.err("用户不存在");
        }
        // 返回用户信息
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(one, userInfo);
        return R.ok(userInfo);
    }

    @GetMapping("/getApiPaths")
    public R<Set<String>> getApiPaths(String username) {
        Set<String> apiPaths = userService.getApiPaths(username);
        if (apiPaths.isEmpty()) {
            return R.err("请先设置用户权限");
        }
        return R.ok(apiPaths);
    }
}
